<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;

class WxLoginController extends Controller
{
    use CurlTrait;
    public static $OK = 0;
    public static $IllegalAesKey = -41001;
    public static $IllegalIv = -41002;
    public static $IllegalBuffer = -41003;
    public static $DecodeBase64Error = -41004;

    private $appid;
    private $sessionKey;
    private $code;

    public function  login(Request $request){
        $this->code = $request->input('code');
        if(!$this->code){
            return false;
        }
        $this->appId = env('APPID', 'wxccd1bbac048b5528');
        $this->secret = env('SECRET', 'bd87727fe95b99ae11840a66d24978ab');
        $apiUrl = env('WX_SESSION_KEY_API', 'https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code');
        $apiUrl = str_replace('APPID', $this->appId, $apiUrl);
        $apiUrl = str_replace('SECRET', $this->secret, $apiUrl);
        $apiUrl = str_replace('JSCODE', $this->code, $apiUrl);
        $resultJson = $this->curlCallGet($apiUrl);
        $result = json_decode($resultJson, true);
        if(isset($result['openid']) && isset($result['session_key'])){
            return json_encode($result);
        }else{
            return json_encode(array('error', 'api call fail'));exit;
        }
    }


    public function getUserInfo(Request $request){
        $data = null;
        $this->sessionKey = $request->session()->get('session_key');
        $encryptedData = $request->input('encryptedData');
        $iv = $request->input('iv');
        $errCode = $this->decryptData($encryptedData, $iv, $data );

        if ($errCode == 0) {
            print($data . "\n");
        } else {
            print($errCode . "\n");
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function isUserOpenIdExist(Request $request)
    {
        $openId = $request->input('openId');
        if(!isset($openId)){
            return false;
        }
        $user = new User();
        $result = $user->isUserOpenIdExist($openId);
        if($result) {
            echo json_encode(array('result' => 1));
            exit;
        }else{
            echo json_encode(array('result' => 0));
            exit;
        }

    }
    /**
     * 检验数据的真实性，并且获取解密后的明文.
     * @param $encryptedData string 加密的用户数据
     * @param $iv string 与用户数据一同返回的初始向量
     * @param $data string 解密后的原文
     *
     * @return int 成功0，失败返回对应的错误码
     */
    public function decryptData( $encryptedData, $iv, &$data )
    {
        if (strlen($this->sessionKey) != 24) {
            return $this::$IllegalAesKey;
        }
        $aesKey=base64_decode($this->sessionKey);


        if (strlen($iv) != 24) {
            return $this::$IllegalIv;
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        var_dump($this->sessionKey, $aesKey, $aesIV, $result);exit;
        $dataObj=json_decode( $result );
        if( $dataObj  == NULL )
        {
            return $this::$IllegalBuffer;
        }
        if( $dataObj->watermark->appid != $this->appid )
        {
            return $this::$IllegalBuffer;
        }
        $data = $result;
        return $this::$OK;
    }
}
